package com.wutuo.aggragation.report.service;

import cn.apestar.util.CommonUtil;
import com.wutuo.aggragation.report.component.MonthComparetor;
import com.wutuo.aggragation.report.component.SignReportDataConvert;
import com.wutuo.aggragation.report.component.TaskTypeComparetor;
import com.wutuo.aggragation.report.dao.SignReportMapper;
import com.wutuo.aggragation.report.response.ListMonthSignDataItem;
import com.wutuo.aggragation.report.response.ListMonthSignTaskItem;
import com.wutuo.aggragation.report.response.ListMonthTaskDataItem;
import com.wutuo.aggragation.report.response.ListMonthTaskDetailItem;
import com.wutuo.aggragation.report.vo.TaskTypeMonthSignNumber;
import com.wutuo.aggragation.rollcall.service.RollCallTaskService;
import com.wutuo.aggragation.rollcall.vo.SimpleTaskVo;
import com.wutuo.enums.TaskType;
import com.wutuo.roster.api.request.SearchRosterRequest;
import com.wutuo.roster.api.response.RosterResponse;
import com.wutuo.roster.provider.service.RosterService;
import com.wutuo.util.PageUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.SetUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 标题、简要说明. <br> 类详细说明.
 * <p/>
 * Copyright: Copyright (c) 2016年4月23日 上午8:22:06
 * <p/>
 * Company: 网龙公司
 * <p/>
 * 午托点名　晚托点名，午托校接　，晚托校接，其他
 *
 * @author Shunqin.Chen
 * @version 1.0.0
 */
@Service
public class SignReportService {

    private Logger logger = LoggerFactory.getLogger(SignReportService.class);

    @Autowired
    private RollCallTaskService rollCallTaskService;

    @Autowired
    private RosterService rosterService;

    @Autowired
    SignReportMapper signReportMapper;

    public List<ListMonthSignDataItem> listMonthSignData(int page, int size, Long institutionId) {

        List<SimpleTaskVo> simpleTaskVos = signReportMapper.statisTaskTypeForMonth(institutionId);
        if (CollectionUtils.isEmpty(simpleTaskVos)) {
            return Collections.emptyList();
        }

        Set<String> months = new TreeSet<>(new MonthComparetor());
        for (SimpleTaskVo item : simpleTaskVos) {
            months.add(item.getTaskMonth());
        }
        SetUtils.orderedSet(months);

        // Count children
        SearchRosterRequest searchRosterRequest = new SearchRosterRequest();
        searchRosterRequest.setCmId(String.valueOf(institutionId));
        searchRosterRequest.setDelFlag(true);
        int childrenCount = rosterService.countInstitutionChildren(searchRosterRequest);

        logger.info("total children count:{}", childrenCount);

        List<TaskTypeMonthSignNumber> taskTypeMonthSignNumbers = signReportMapper
                .statsTaskTypeMonthSignNumber(institutionId);

        Map<Pair<String, String>, TaskTypeMonthSignNumber> taskTypeMonthDataMap = SignReportDataConvert
                .convertTaskTypeMonthSignNumberToMap(taskTypeMonthSignNumbers);

        List<ListMonthSignDataItem> response = new ArrayList<>();
        for (String month : months) {
            ListMonthSignDataItem monthItem = new ListMonthSignDataItem();
            List<ListMonthSignTaskItem> monthDetails = new ArrayList<>();
            monthItem.setMonth(month);
            monthItem.setTotal(childrenCount);
            monthItem.setDetail(monthDetails);

            Set<String> types = new HashSet<>(); // 用于前端显示：如果类型不齐，要补齐
            for (SimpleTaskVo item : simpleTaskVos) {
                if (month.equals(item.getTaskMonth())) {
                    Pair<String, String> key = new ImmutablePair<>(item.getTaskType(), item.getTaskMonth());
                    TaskTypeMonthSignNumber monthData = taskTypeMonthDataMap.get(key);
                    ListMonthSignTaskItem monthDetailItem = new ListMonthSignTaskItem();
                    monthDetailItem.setType(item.getTaskType());
                    monthDetailItem.setTypeName(TaskType.getText(item.getTaskType()));
                    monthDetailItem.setCount(monthData == null ? 0 : monthData.getSignNum());
                    monthDetails.add(monthDetailItem);

                    types.add(item.getTaskType());
                }
            }

            if (types.size() < 5) {
                for (TaskType item : TaskType.values()) {
                    if (types.contains(item.getValue())) {
                        continue;
                    }
                    ListMonthSignTaskItem monthDetailItem = new ListMonthSignTaskItem();
                    monthDetailItem.setType(item.getValue());
                    monthDetailItem.setTypeName(TaskType.getText(item.getValue()));
                    monthDetailItem.setCount(0);
                    monthDetails.add(monthDetailItem);
                    Collections.sort(monthDetails, new TaskTypeComparetor());
                }
            }

            response.add(monthItem);

        }

        return PageUtil.getSubPage(response, page, size);
    }

    public List<ListMonthTaskDataItem> listMonthTaskDataDetail(String month, String type, Long institutionId) {
        List<ListMonthTaskDataItem> response = signReportMapper.statsMonthAndType(month, type, institutionId);
        if (CollectionUtils.isEmpty(response)) {
            return Collections.emptyList();
        }

        List<Long> rosterIds = new ArrayList<>();
        for (ListMonthTaskDataItem item : response) {
            rosterIds.add(item.getChildId());
        }

        // Count children
        SearchRosterRequest searchRosterRequest = new SearchRosterRequest();
        searchRosterRequest.setCmInstitutionId(institutionId);
        searchRosterRequest.setRosterIds(rosterIds);
        List<RosterResponse> children = rosterService.lisForPage(searchRosterRequest);

        Map<String, RosterResponse> rosterMap = CommonUtil.listToObject(children, "id");

        for (ListMonthTaskDataItem item : response) {
            if (item.getChildId() == null) {
                continue;
            }
            RosterResponse childInfo = rosterMap.get(String.valueOf(item.getChildId()));
            if (childInfo == null) {
                continue;
            }
            item.setChildName(childInfo.getName());
            item.setImg(childInfo.getPhoto());
            item.setSex(childInfo.getSex());
            item.setYear(String.valueOf(childInfo.getYear()));

        }

        return response;

    }

    public List<ListMonthTaskDetailItem> listMonthTaskSignRecord(String month, String taskType, Long institutionId,
                                                                 Long childId) {

        return signReportMapper.statsSignDay(month, taskType, institutionId, childId);
    }

}


